package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

/**
 * @program: bookstore
 * @description:
 * @create: 2024-10-08 14:28
 **/
public class JwtUtil {
    private static final String secretKey = "天王盖地虎，宝塔镇河妖";
    //    生成jwt
    public static String createJWT(Map map) throws JOSEException {
        //1、头部
        JWSHeader header = new JWSHeader
                .Builder(JWSAlgorithm.HS256)//指定加密算法
                .type(JOSEObjectType.JWT).build();//指定常量

        //2、载荷（用户信息）

        Payload payload = new Payload(map);

        //3、签名（加密（头部+载荷+秘钥））
        JWSObject jwsObject = new JWSObject(header, payload);

        MACSigner macSigner = new MACSigner(secretKey);
        jwsObject.sign(macSigner);//指定秘钥后加密

        //4、jwt字符串
        return jwsObject.serialize();
    }

    /**
     * 解密jwt的方法
     */
    public static boolean decode(String jwt) throws ParseException, JOSEException {
        //通过jwt字符串得到签名对象
        JWSObject jwsObject=JWSObject.parse(jwt);
        MACVerifier macVerifier=new MACVerifier(secretKey);
        return jwsObject.verify(macVerifier);//解密
    }

    /**
     * 获取jwt中用户信息
     */
    public static Map getUserMap(String jwt) throws ParseException {
        JWSObject jwsObject=JWSObject.parse(jwt);
        Payload payload = jwsObject.getPayload();
        return payload.toJSONObject();//存入载荷的用户map
    }
}
